import React from "react";
export default class Uploader extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            btnText: '点击上传',
            isUploading: false
        };
    }

    componentDidMount() {
        $(this.refs.file).on('change', (e)=> {
            if (e.target.files.length > 0) {
                this.setState({
                    btnText: '上传中',
                    isUploading: true
                });
                this.uploadFile(e.target.files[0]);
            }
        });
    }

    uploadFile(file) {
        const xhr = new XMLHttpRequest();
        let data = new FormData;
        data.append(this.props.name, file);
        for (var key in this.props.params) {
            if (this.props.params.hasOwnProperty(key)) {
                data.append(key, this.props.params[key]);
            }
        }
        xhr.open('POST', this.props.url, true);
        xhr.onreadystatechange = () => {
            if (xhr.readyState == 4 && xhr.status == 200) {
                this.setState({isUploading: false, btnText: '上传完成'});
                //上传完成了
                let resp = JSON.parse(xhr.responseText);
                this.props.onUploaded(this.props.origin + '/' + resp.key);
            }
        };
        xhr.onerror = function (error) {
            this.setState({isUploading: false, btnText: '上传出错，重新上传'});
        };
        xhr.upload && (xhr.upload.onprogress = (e)=> {
            if (e.lengthComputable) {
                let process = parseInt((e.loaded / e.total) * 100) + '%';
                this.setState({btnText: '上传中' + process});
            }
        });
        xhr.send(data);
    }

    componentDidUnmout() {
        $(this.refs.file).off('change');
    }

    render() {
        return (
            <div>
                <div className="component-uploader">
                    <input multiple={this.props.multi} disabled={this.state.isUploading} type="file"
                           accept={this.props.fileType} ref="file"/>
                    <button className="btn btn-primary btn-block">{this.state.btnText}</button>
                </div>
            </div>
        )
    }
}

Uploader.propTypes = {
    name: React.PropTypes.string,
    params: React.PropTypes.object,
    url: React.PropTypes.string,
    fileType: React.PropTypes.string,
    onUploaded: React.PropTypes.func.isRequired,
    multi: React.PropTypes.bool,
    origin: React.PropTypes.string
};

Uploader.defaultProps = {
    name: 'file',
    params: {
        token: window.config.qiniu.token
    },
    url: 'http://up.qiniu.com',
    fileType: '*/*',
    multi: false,
    origin: window.config.qiniu.origin
};